package com.wry.myphotowall.fragment;

import android.animation.ObjectAnimator;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;
import com.wry.myphotowall.R;
import com.wry.myphotowall.activity.PhotoPickerActivity;
import com.wry.myphotowall.adapter.PhotoPagerAdapter;
import com.wry.myphotowall.adapter.PhotoWallAdapter;
import com.wry.myphotowall.listener.OnPagerCLickListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PhotoViewFragment extends Fragment {

    private ArrayList<String> mPaths;
    private ViewPager mViewPager;
    private PhotoPagerAdapter mPagerAdapter;

    private RelativeLayout mTopbar;//顶部布局
    private TextView mToptv;//顶部图片张数显示
    private TextView tvPreview;//预览  在该页面不做显示
    TextView tvComplete;//完成
    private RelativeLayout mBottombar;//底部布局
    private TextView tvSelected;//选择

    public final static String ARG_PATH = "PATHS";
    public final static String ARG_POSITION = "CURRENT_POSITION";
    public final static String ARG_MAXCOUNT = "MAX_SELECT_COUNT";
    public final static String ARG_THUMBNAIL_TOP = "THUMBNAIL_TOP";
    public final static String ARG_THUMBNAIL_LEFT = "THUMBNAIL_LEFT";
    public final static String ARG_THUMBNAIL_WIDTH = "THUMBNAIL_WIDTH";
    public final static String ARG_THUMBNAIL_HEIGHT = "THUMBNAIL_HEIGHT";
    public final static String ARG_HAS_ANIM = "HAS_ANIM";

    public final static long ANIM_DURATION = 200L;
    private int currentPosition = 0;

    private int thumbnailTop = 0;
    private int thumbnailLeft = 0;
    private int thumbnailWidth = 0;
    private int thumbnailHeight = 0;

    private int mDesireSelectCount;
    private boolean hasAnim = false;
    private boolean isShowBottomBar = true;

    private Drawable drawable_unchecked;
    private Drawable drawable_checked;

    Animation mTranslateInAnimation, mTranslateOutAnimation;
    Animation mTranslateInAnimation_bottom, mTranslateOutAnimation_bottom;


    public static PhotoViewFragment newInstance(List<String> paths, int position, int maxSelectCount) {

        PhotoViewFragment fragment = new PhotoViewFragment();

        Bundle args = new Bundle();
        args.putStringArray(ARG_PATH, paths.toArray(new String[paths.size()]));
        args.putInt(ARG_POSITION, position);
        args.putBoolean(ARG_HAS_ANIM, false);
        args.putInt(ARG_MAXCOUNT, maxSelectCount);
        fragment.setArguments(args);

        return fragment;
    }

    public static PhotoViewFragment newInstance(List<String> paths, int position, int maxSelectCount, int[] screenLocation, int thumbnailWidth, int thumbnailHeight) {

        PhotoViewFragment fragment = newInstance(paths, position, maxSelectCount);
        fragment.getArguments().putInt(ARG_THUMBNAIL_LEFT, screenLocation[0]);
        fragment.getArguments().putInt(ARG_THUMBNAIL_TOP, screenLocation[1]);
        fragment.getArguments().putInt(ARG_THUMBNAIL_WIDTH, thumbnailWidth);
        fragment.getArguments().putInt(ARG_THUMBNAIL_HEIGHT, thumbnailHeight);
        fragment.getArguments().putBoolean(ARG_HAS_ANIM, true);
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 定义进入与退出动画
        mTranslateInAnimation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, -1.5f, Animation.RELATIVE_TO_SELF,
                0);
        mTranslateInAnimation.setDuration(ANIM_DURATION);
        mTranslateInAnimation_bottom = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, 1.5f, Animation.RELATIVE_TO_SELF,
                0);
        mTranslateInAnimation_bottom.setDuration(ANIM_DURATION);
        mTranslateOutAnimation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
                -1.5f);
        mTranslateOutAnimation.setDuration(ANIM_DURATION);
        mTranslateOutAnimation_bottom = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
                1.5f);
        mTranslateOutAnimation_bottom.setDuration(ANIM_DURATION);
        mTranslateOutAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mTopbar.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mTranslateOutAnimation_bottom.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mBottombar.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mPaths = new ArrayList<>();

        Bundle bundle = getArguments();
        if (bundle != null) {
            String[] pathArr = bundle.getStringArray(ARG_PATH);
            mPaths.clear();
            if (pathArr != null) {
                mPaths = new ArrayList<>(Arrays.asList(pathArr));
            }

            hasAnim = bundle.getBoolean(ARG_HAS_ANIM);
            currentPosition = bundle.getInt(ARG_POSITION);
            mDesireSelectCount = bundle.getInt(ARG_MAXCOUNT);
            thumbnailTop = bundle.getInt(ARG_THUMBNAIL_TOP);
            thumbnailLeft = bundle.getInt(ARG_THUMBNAIL_LEFT);
            thumbnailWidth = bundle.getInt(ARG_THUMBNAIL_WIDTH);
            thumbnailHeight = bundle.getInt(ARG_THUMBNAIL_HEIGHT);
        }

        mPagerAdapter = new PhotoPagerAdapter(getActivity(), mPaths);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_photo_view, container, false);

        mViewPager = (ViewPager) rootView.findViewById(R.id.vp_photos);
        mViewPager.setPadding(0, 0, 0, 0);

        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setCurrentItem(currentPosition);
//        mViewPager.setOffscreenPageLimit(5);

        drawable_unchecked = ContextCompat.getDrawable(getActivity(), R.drawable.selectbox_n);
        drawable_checked = ContextCompat.getDrawable(getActivity(), R.drawable.selectbox_marked);

        mViewPager = (ViewPager) rootView.findViewById(R.id.vp_photos);

        mTopbar = (RelativeLayout) getActivity().findViewById(R.id.layout_top_actionbar);
        mBottombar = (RelativeLayout) getActivity().findViewById(R.id.layout_bottom_actionbar);
        tvComplete = (TextView) getActivity().findViewById(R.id.tv_commit);
        tvPreview = (TextView) getActivity().findViewById(R.id.tv_preview);
        tvSelected = (TextView) getActivity().findViewById(R.id.tv_selectbox);
        mToptv = (TextView) getActivity().findViewById(R.id.tv_back);


        drawable_unchecked.setBounds(0, 0, drawable_unchecked.getMinimumWidth(), drawable_unchecked.getMinimumHeight());
        tvSelected.setCompoundDrawables(drawable_unchecked, null, null, null);
        tvSelected.setSelected(false);
        //更新第一张预览图片的selectbox
        if (PhotoWallAdapter.mSelectedImage.contains(
                mPaths.get(currentPosition))) {
            drawable_checked.setBounds(0, 0, drawable_checked.getMinimumWidth(), drawable_checked.getMinimumHeight());
            tvSelected.setCompoundDrawables(drawable_checked, null, null, null);
            tvSelected.setSelected(true);
            tvComplete.setEnabled(true);
            tvComplete.setText(String.format("%s(%d/%d)", getString(R.string.action_done)
                    , PhotoWallAdapter.mSelectedImage.size(), mDesireSelectCount));
            tvComplete.setBackgroundResource(R.drawable.bg_complete_enable);
            tvComplete.setPadding(getResources().getDimensionPixelSize(R.dimen.x6), 0, getResources().getDimensionPixelSize(R.dimen.x6), 0);
        }
        //进入pager显示Top TextView(eg:2/19)
        mToptv.setText(String.format("%d/%d", currentPosition + 1,
                mPaths.size()));

        if (savedInstanceState == null && hasAnim) {

            ViewTreeObserver observer = mViewPager.getViewTreeObserver();
            observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {

                    mViewPager.getViewTreeObserver().removeOnPreDrawListener(this);

                    int[] screenLocation = new int[2];
                    mViewPager.getLocationOnScreen(screenLocation);
                    thumbnailLeft = thumbnailLeft - screenLocation[0];
                    thumbnailTop = thumbnailTop - screenLocation[1];

                    runEnterAnimation();

                    return true;
                }
            });
        }

        mPagerAdapter.setOnPagerCLickListener(new OnPagerCLickListener() {
            @Override
            public void onPagerClick() {
                if (isShowBottomBar) {
                    mTopbar.startAnimation(mTranslateOutAnimation);
                    mBottombar.startAnimation(mTranslateOutAnimation_bottom);
                    isShowBottomBar = !isShowBottomBar;
                    ((PhotoPickerActivity) getActivity()).setFullScreen(true);
                } else {
                    mTopbar.setVisibility(View.VISIBLE);
                    mTopbar.startAnimation(mTranslateInAnimation);
                    mBottombar.setVisibility(View.VISIBLE);
                    mBottombar.startAnimation(mTranslateInAnimation_bottom);
                    isShowBottomBar = !isShowBottomBar;
                    ((PhotoPickerActivity) getActivity()).setFullScreen(false);
                }
            }
        });

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                hasAnim = currentPosition == position;
                if (PhotoWallAdapter.mSelectedImage.
                        contains(mPaths.get(position))) {
                    drawable_checked.setBounds(0, 0, drawable_checked.getMinimumWidth(), drawable_checked.getMinimumHeight());
                    tvSelected.setCompoundDrawables(drawable_checked, null, null, null);
                    tvSelected.setSelected(true);
                } else {
                    drawable_unchecked.setBounds(0, 0, drawable_unchecked.getMinimumWidth(), drawable_unchecked.getMinimumHeight());
                    tvSelected.setCompoundDrawables(drawable_unchecked, null, null, null);
                    tvSelected.setSelected(false);
                }
                mToptv.setText(String.format("%d/%d", position + 1,
                        mPaths.size()));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        tvSelected.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int pos = mViewPager.getCurrentItem();
                if (PhotoWallAdapter.mSelectedImage.
                        contains(mPaths.get(pos))) {
                    drawable_unchecked.setBounds(0, 0, drawable_unchecked.getMinimumWidth(), drawable_unchecked.getMinimumHeight());
                    tvSelected.setCompoundDrawables(drawable_unchecked, null, null, null);
                    tvSelected.setSelected(false);
                    PhotoWallAdapter.mSelectedImage.remove(mPaths.get(pos));
                    if (PhotoWallAdapter.mSelectedImage.size() == 0) {
                        tvPreview.setEnabled(false);
                        tvPreview.setText(R.string.preview);
                        tvComplete.setEnabled(false);
                        tvComplete.setText(R.string.action_done);
                        tvComplete.setBackgroundResource(R.drawable.bg_complete_unenable);
                        tvComplete.setPadding(getResources().getDimensionPixelSize(R.dimen.x14), 0, getResources().getDimensionPixelSize(R.dimen.x14), 0);
                    } else {
                        tvPreview.setEnabled(true);
                        tvPreview.setText(getResources().getString(R.string.preview)
                                + "(" + PhotoWallAdapter.mSelectedImage.size() + ")");
                        tvComplete.setEnabled(true);
                        tvComplete.setText(String.format("%s(%d/%d)", getString(R.string.action_done)
                                , PhotoWallAdapter.mSelectedImage.size(), mDesireSelectCount));
                        tvComplete.setBackgroundResource(R.drawable.bg_complete_enable);
                        tvComplete.setPadding(getResources().getDimensionPixelSize(R.dimen.x6), 0, getResources().getDimensionPixelSize(R.dimen.x6), 0);
                    }
                } else {
                    if (PhotoWallAdapter.mSelectedImage.size() < mDesireSelectCount) {
                        drawable_checked.setBounds(0, 0, drawable_checked.getMinimumWidth(), drawable_checked.getMinimumHeight());
                        tvSelected.setCompoundDrawables(drawable_checked, null, null, null);
                        tvSelected.setSelected(true);
                        PhotoWallAdapter.mSelectedImage.add(mPaths.get(pos));
                        tvPreview.setEnabled(true);
                        tvPreview.setText(getResources().getString(R.string.preview)
                                + "(" + PhotoWallAdapter.mSelectedImage.size() + ")");
                        tvComplete.setEnabled(true);
                        tvComplete.setText(String.format("%s(%d/%d)", getString(R.string.action_done)
                                , PhotoWallAdapter.mSelectedImage.size(), mDesireSelectCount));
                        tvComplete.setBackgroundResource(R.drawable.bg_complete_enable);
                        tvComplete.setPadding(getResources().getDimensionPixelSize(R.dimen.x6), 0, getResources().getDimensionPixelSize(R.dimen.x6), 0);
                    } else {
                        Toast.makeText(getActivity(), R.string.msg_amount_limit, Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        return rootView;
    }


    private void runEnterAnimation() {
        final long duration = ANIM_DURATION;
        ViewHelper.setPivotX(mViewPager, 0);
        ViewHelper.setPivotY(mViewPager, 0);
        ViewHelper.setScaleX(mViewPager, (float) thumbnailWidth / mViewPager.getWidth());
        ViewHelper.setScaleY(mViewPager, (float) thumbnailHeight / mViewPager.getHeight());
        ViewHelper.setTranslationX(mViewPager, thumbnailLeft);
        ViewHelper.setTranslationY(mViewPager, thumbnailTop);

        ViewPropertyAnimator.animate(mViewPager)
                .setDuration(duration)
                .scaleX(1)
                .scaleY(1)
                .translationX(0)
                .translationY(0)
                .setInterpolator(new DecelerateInterpolator());

        ObjectAnimator bgAnim = ObjectAnimator.ofInt(mViewPager.getBackground(),
                "alpha", 0, 255);
        bgAnim.setDuration(duration);
        bgAnim.start();
        ObjectAnimator colorizer = ObjectAnimator.ofFloat(PhotoViewFragment.this,
                "saturation", 0, 1);
        colorizer.setDuration(duration);
        colorizer.start();
    }

    public void runExitAnimation(final Runnable endAction) {

        if (!getArguments().getBoolean(ARG_HAS_ANIM, false) || !hasAnim) {
            endAction.run();
            return;
        }
        final long duration = ANIM_DURATION;
        ViewPropertyAnimator.animate(mViewPager)
                .setDuration(duration)
                .setInterpolator(new AccelerateInterpolator())
                .scaleX((float) thumbnailWidth / mViewPager.getWidth())
                .scaleY((float) thumbnailHeight / mViewPager.getHeight())
                .translationX(thumbnailLeft)
                .translationY(thumbnailTop)
                .setListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        endAction.run();
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }
                });

        ObjectAnimator bgAnim =
                ObjectAnimator.ofInt(mViewPager.getBackground(), "alpha", 0);
        bgAnim.setDuration(duration);
        bgAnim.start();

        ObjectAnimator colorizer =
                ObjectAnimator.ofFloat(PhotoViewFragment.this, "saturation", 1, 0);
        colorizer.setDuration(duration);
        colorizer.start();
    }
}
